<style scoped>
  .weui-form-preview__hd label, .weui-form-preview__hd em {
    font-size: .9em !important;
  }
  .rj-cell.max span{
    font-size: 16px;
    padding-right: 20px;
  }
  .rj-cell label {
    color: #333;
    font-size: 14px;
    width: 44%;
    display: inline-block;
    padding: 5px 3%;
    text-align: right;
  }
  .rj-cell span {
    font-size: 14px;
    color: #333;
    display: inline-block;
    width: 50%;
  }
  .rj-cell.note label{
    float: left;
  }
  .rj-cell.note span{
    width: 80%;
    display: inline-block;
  }
  .weui-cells {
    margin-top: 0;
  }
  .weui-cells_form {
    background: #fbfbfb;
  }
  .weui-cell {
    background: #fff;
  }
  #acts span {
    font-size: 14px;
  }
  .halfbtn {
    display: inline-block;
    width: 49%;
  }
  .weui-label{
    /*width: 130px;*/
    text-align: left;
  }

  .weui-select {
    height: auto;
    line-height: normal;
  }
  *{
    list-style:none;
  }
  /*body{*/

  /*}*/
  .weui-cell_select {
    padding: 10px 15px;
  }
  .weui-cells__title {
    text-align: left;
  }
  .hide {
    display: none;
  }
  #acts {
    font-size: 0;
  }
  #acts span {
    font-size: 14px;
  }
  .section {
    margin: 5px;
    border-radius: 5px;
  }
</style>
<template>
  <div class="comon">
    <div class="rj-wrap">
      {{title}}
      <a href="javascript:;" @click="$router.back(-1)" style="position: absolute; left: 10px; top: 8px">
        <img src="@/assets/back.png" style="width: 20px" />
      </a>
    </div>
    <div class="weui-cells weui-cells_form">
        <form method="post" id="formid">
          <input type="hidden" name="type" :value="baseInfo.picktype" />
          <input type="hidden" name="produceplanid" :value="baseInfo.produceplanid" />
          <input type="hidden" name="linkedid" :value="baseInfo.guid" />
          <input type="hidden" name="srguid" :value="baseInfo.strmid" />
          <input type="hidden" name="departid" :value="baseInfo.departmentid" />
          <input type="hidden" name="orgguid" :value="baseInfo.orgid" />
          <input type="hidden" name="status" value="1" />
          <div class="cellgroup">
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">领料单编号</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" readonly :value="baseInfo.code" name="">
            </div>
          </div>
<!--          <div class="weui-cell">-->
<!--            <div class="weui-cell__hd"><label class="weui-label">入库类型</label></div>-->
<!--            <div class="weui-cell__bd">-->
<!--              <input class="weui-input" readonly name="typeName" value="生产退料">-->
<!--            </div>-->
<!--          </div>-->
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">入库库房</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" readonly name="" :value="baseInfo.strname">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">库存组织</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" readonly  type="text"  name="orgname" :value="baseInfo.orgname">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">所在班组</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" readonly  type="text"  name="" :value="baseInfo.deptName">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">创建时间</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" readonly type="text" name="" :value="baseInfo.createtime">
            </div>
          </div>
        </div>
          <div class="weui-panel__hd" style="text-align: left;">货品明细
            (<span style="color: red;text-align: left;font-size: 12px;">请选择要退的货品</span>)
          </div>
          <div class="weui-panel__bd section" style="background: #fff;width: auto;">
            <MaterRetApplyItem v-for="(item, index) in baseInfo.items" :key="index" :itemNo="index" :isLast="index+1 == baseInfo.items.length" :applyid="id" :picktype="baseInfo.picktype" :product="item" @doAddItem="addItem(index + 1)" @doDelItem="delItem" @changeData="takeItem"></MaterRetApplyItem>
          </div>
          <div ref="actHtml" class="fixcont">
            <div class="weui-btn-area">
              <a class="weui-btn weui-btn_primary halfbtn subbtn"  href="javascript:" @click="send">提交</a>
              <a class="weui-btn weui-btn_primary halfbtn"  href="javascript:" @click="$router.back(-1)" id="sub">返回</a>
            </div>
          </div>
      </form>
    </div>
  </div>
</template>

<script>
  import MaterRetApplyItem from "./MaterRetApplyItem";
  export default {
    name: 'ApplyBack2',
    data () {
      return {
        openid: localStorage.openid,
        id: '',
        baseInfo: {},
        items: [],
        products: [],
        specifications: [],
        oitems: [0],
        nodeid: '',
        title: '退料申请',
        model: {
          items: []
        }
      }
    },
    components: {MaterRetApplyItem},
    created() {
      window.addEventListener('setItem', ()=> {
        this.openid = localStorage.getItem('openid');
      })
    },
    mounted () {
      //提交操作定位到页面底部
      //$('#bmlogs').css('margin-bottom', this.$refs.actHtml.offsetHeight);

      let that = this;
      this.id = this.$route.query.id;
      //获取回显数据
      this.getApplyInfo(this.$route.query.id);

    },
    computed: {
    },
    methods: {
      takeItem: function(val) {
        // if (!val) return;
        console.log('takeItem val:', val)
        if (!this.model.items.some(item => item.index == val.index)) {
          this.model.items.push(val);
        }
        console.log('takeItem this.model', this.model)
        console.log('takeItem this.model.items', this.model.items)
      },
      addItem: function(index) {
        this.oitems.push(index);
      },
      delItem: function(index) {
        this.model.items = this.model.items.filter(item => item.index != index)
        console.log('delItem this.model.items:', this.model.items)
      },
      getApplyInfo: function(id) {
        // this.baseInfo = {"id":3068, "code":"PL220675", "orgId":4, "toOrgId":null, "deptId":112, "platformId":null, "toPlatformId":null, "status":100, "condition":null, "createName":"张福", "createBy":7, "updateBy":null, "createTime":null, "updateTime":null, "remark":null, "businessType":null, "baseItems":null, "cusCtractId":null, "projectId":null, "projId":null, "supplierId":null, "fullName":null, "params":null, "busTable":null, "orgFlag":null, "keyword":null, "operation":null, "guid":"947f0edf2fb34493a2fb126776e8bdf4", "produceplanid":"139e0e11036e4caba19f5873b7681db9", "departmentid":"12BC95375FB84CCBAF2C24396D778002", "picktype":2, "ordertime":null, "strmid":"542414C110644DD9B7D0E881968B55AE", "strm":28, "operatorid":"DCF98EC134A54820A1C5E951FF453B83", "lastupdate":"2022-06-28", "orgid":"162AE70D01A6427D916688DA1374D0EF", "orgname":"集宁工厂", "weightsum":0, "pricesum":0, "flowid":"30", "flag":1, "deptName":"传统业务部-华北", "createtime":"2022-06-28", "items":[{"searchValue":null, "createBy":null, "createTime":null, "updateBy":null, "updateTime":null, "remark":"", "params":{}, "guid":"955e2db16ef44a4cb5194a79ae4a6a20", "pickinglistid":"947f0edf2fb34493a2fb126776e8bdf4", "strmid":"542414C110644DD9B7D0E881968B55AE", "sthid":"b03e93bfad244f0cbb0797578ff3c518", "productid":"3d7c5016fd644a4daa68e613758d79bd", "product":"包装物", "produceplace":null, "weight":20, "speid":"00851ed62856419baa12ff71c81d02b5", "spename":"轻食营养泥 50*37*32（外径）钉箱", "pricesum":0, "price":null, "stockunit":"个", "stockunitid":5, "picktype":4, "cospguid":null, "outweight":100, "searchflag":null, "picktypename":"辅料", "proflags":null }, {"searchValue":null, "createBy":null, "createTime":null, "updateBy":null, "updateTime":null, "remark":"", "params":{}, "guid":"fe0702ecfe55449cb8c3168290379e03", "pickinglistid":"947f0edf2fb34493a2fb126776e8bdf4", "strmid":"542414C110644DD9B7D0E881968B55AE", "sthid":"b03e93bfad244f0cbb0797578ff3c518", "productid":"3d7c5016fd644a4daa68e613758d79bd", "product":"包装物", "produceplace":null, "weight":2, "speid":"01d63fec4cb643a7b1777a18da4a38e5", "spename":"絮凝剂", "pricesum":0, "price":null, "stockunit":"公斤", "stockunitid":3, "picktype":4, "cospguid":null, "outweight":23.3, "searchflag":null, "picktypename":"辅料", "proflags":null } ], "stats":null, "notInStats":null, "orgIds":null, "andorgIds":null, "anddeptIds":null, "statusname":"已出库", "search":null, "nodes":null, "ids":null, "departmentname":null, "produceplanCode":"PP220659", "produceplanName":"0628生产计划", "produceplanstart":"2022-06-28 00:00:00", "strname":"康莱纳（集宁工厂）", "picktypename":"辅料领料", "scrapapplyCount":null, "materialretapplyCount":null, "whinapplyCount":null, "className":"Pickinglist"};
        this.axios({
          method: 'get',
          url: `/prod-api/produce/pickinglist/${id}`,
        }).then(response => {
          if (response.data.code == 200) {
            let data = response.data;
            this.baseInfo = data.data || {};
            this.items = data.items;
            this.products = data.products;
            this.specifications = data.specifications;
            // this.baseItems = response.data.items;
          } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
            //不不设置提示
          } else {
            this.toastError('系统错误');
          }
          this.isReady = true;
        });
      },
      send: function() {
        let that = this;
        if (!this.model.items || this.model.items.length <= 0) {
          this.toastText('请选择货品明细！');
          return false;
        }

        //防止重复提交
        $('.subbtn').attr("disabled",true).css("pointer-events","none");
        //显示提交状态
        $.showLoading("正在提交");

        let postData = this.serialize2Obj($("#formid").serializeArray());
        postData.pickinglistid = this.baseInfo.guid;
        postData.items = that.model.items;
        this.axios({
          method: 'post',
          url: '/prod-api/produce/materialretapply/save',
          data: postData
        }).then(response => {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();

          if(response.data.code == 200){
            this.toastText('操作成功!');
            this.$router.push({name: 'ApplyBackList2'});
          }else if (response.data.msg == 'outlogin'){
            this.toastText('请重新登录!');
          } else if (response.data.msg == 'canotopt') {
            this.toastText('不允许的操作！');
          } else if (response.data.msg == 'error'){
            this.toastError('系统错误!');
          } else if(response.data.msg) {
            this.toastText(response.data.msg);
          } else {
            this.toastError('系统错误!');
          }
        }).catch(function (error) {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();
          that.toastError('系统错误');
        });

      },
      //判断明细产品是否重复
      checkProduct: function () {
        let parr1 = [];
        let parr2 = [];
        for (let i=0; i<$('.oitem').length; i++) {
          parr1.push({[$('.product').eq(i).val()]: $('.specif').eq(i).val()});
          parr2.push({[$('.product').eq(i).val()]: $('.specif').eq(i).val()});
        }
        //json数组去重
        for (var i = 0; i < parr2.length; i++) {
          for (var j =i+1; j <parr2.length; ) {
            if (Object.keys(parr2[i])[0] == Object.keys(parr2[j])[0] && Object.values(parr2[i])[0] == Object.values(parr2[j])[0] ) {
              parr2.splice(j, 1);//去除重复的对象；
            }else {
              j++;
            }
          }
        }
        return parr1.length == parr2.length ? true : false;
      },
    }
  }


</script>
